<?php

/**
 * @filename CommonAction.class.php 
 * @encoding UTF-8 
 * @author nemo.xiaolan <a href="mailto:335454250@qq.com">335454250@qq.com</a>
 * @link <a href="http://www.sep-v.com">http://www.sep-v.com</a>
 * @license http://www.sep-v.com/code-license
 * @datetime 2013-11-11  17:03:55
 * @Description
 * 
 */
class CommonAction extends Action {
    
    protected $user;
    
    protected $isLogin;
    
    protected $workflowAlias;
    
    protected $relation = false;
    
    protected $uneedPermission = array(
        
    );
    
    protected function _filter(&$map) {}
    
    public function _initialize() {
        
        if(false === strpos($_SERVER["HTTP_USER_AGENT"],"Chrome")) {
            $this->errorPage("503", L("browser_not_supported"));
            exit;
        }
        
        if($_SESSION["user"]["id"]) {
            $this->user = $_SESSION["user"];
            $this->isLogin = $this->user["isLogin"] = 1;
            $this->assign("user", $this->user);
        }
        
        
        $this->checkPermission();
        $this->makeQuickActions();
        $this->makeFilter();
        
        $this->assign("_MODULE_", MODULE_NAME);
        $this->assign("_ACTION_", ACTION_NAME);
        
        $this->assign("CTS", CTS);
        
        /**
         * 面包屑导航
         */
        $bnav = C("BCN");
        
        $this->assign("bnavList", $bnavList);
        
        if($this->quickActionTpl) {
            $this->assign("quickActionTpl", $this->quickActionTpl);
        }
        
        import("@.Workflow.Workflow");
        
        
    }
    
    public function makeFilter($name = "") {
        /**
         * 过滤器
         */
        import("@.FilterMaker.FilterMaker");
        $name = $name ? $name : MODULE_NAME;
        $filter = new FilterMaker($name);
        $theFilter = $filter->make();
        $this->assign("theFilter", $theFilter);
    }
    
    private function makeQuickActions() {
//        echo "QuickActions/".GROUP_NAME."/".MODULE_NAME;exit;
        $quickActions = F("QuickActions/".GROUP_NAME."/".MODULE_NAME);
        
        if(!$quickActions) {
            $tmp = require APP_PATH.DS."Conf".DS."quickActions.php";
            $key = GROUP_NAME."/".MODULE_NAME;
            foreach($tmp as $k=>$v) {
                $used = $v["__USED__"];
                unset($v["__USED__"]);
                foreach($used as $u) {
                    $tmpResult[$u] = $v;
                    F("QuickActions/".$u, $tmpResult[$u]);
                }
            }
            $quickActions = array_merge((array)$tmpResult[GROUP_NAME."/".MODULE_NAME], 
                    (array)$tmpResult[GROUP_NAME."/".MODULE_NAME."/".ACTION_NAME]);
        }
        if(!$quickActions) {
            return;
        }
        
        
        
        import('ORG.Util.Auth');//加载类库
        $auth = new Auth();
        
        foreach ($quickActions as $k=>$v) {
            list($action, $bgcolor, $span) = explode("|", $v);
            list($g, $m, $a) = explode("/", $action);
            $a = $a ? $a : "index";
            $authName = sprintf("%s.%s.%s", $g, $m, $a);

            if(!$auth->check($authName, $_SESSION["user"]["id"])) {
                continue;
            }
            $result[$k] = array(
                "action" => "/".$action,
                "icon"  => $icon,
                "bgcolor" => $bgcolor ? $bgcolor : "normal",
                "id" => $id
            );
            if($span) {
                $result[$k]["span"] = sprintf('<span class="label label-important" id="%s"></span>', $span);
            }
        }
        
//        print_r($result);exit;
        $this->assign("QuickActions", $result);
    }

    private function checkPermission(){
        if(strtolower(MODULE_NAME) == "passport" and strtolower(ACTION_NAME) == "login") {
            return true;
        } else if(!$_SESSION["user"]) {
            $this->redirect("/HOME/Passport/login");
        }
        
        if(IS_AJAX) {
            return true;
        }
        
        import('ORG.Util.Auth');//加载类库
        $auth=new Auth();
        $action = ACTION_NAME;
        $action = ACTION_NAME == "insert" ? "add" : $action;
        $action = ACTION_NAME == "update" ? "edit" : $action;
        $rule = sprintf("%s.%s.%s", GROUP_NAME, MODULE_NAME, $action);
        if($action == "doWorkflow") {
            return true;
        }
//        echo $rule;exit;
        if(!$auth->check($rule, $_SESSION["user"]["id"])){
//            echo $rule;exit;
//            $this->errorPage(403);
//            echo "NO PERMISSION";
            //$this->error('你没有权限');
        }else {
            //echo 2;
        }
    }

    protected function _base_filter(&$map) {
        if($_GET["filter_field"] and $_GET["filter_value"]) {
            $map[$_GET["filter_field"]] = array("LIKE", "%".trim($_GET["filter_value"])."%");
        }
        if($_GET["date_start"]) {
            $map["dateline"] = array("EGT", strtotime($_GET["date_start"]));
        }
        if($_GET["date_end"]) {
            $map["dateline"] = array("ELT", strtotime($_GET["date_end"]));
        }
        if($_GET["workflow_node"]) { // 按工作流处理
            $model = D("WorkflowProcess");
            $tmp = $model->where(array(
                "node_id" => $_GET["workflow_node"],
                "status"  => 0
            ))->select();
//            echo $model->getLastSql();exit;
            foreach($tmp as $k=>$v) {
                $ids[] = $v["mainrow_id"];
            }
            $map["id"] = array("IN", implode(",", $ids));
        }
        if(isset($_GET["stock_id"]) and !$_GET["stock_id"]) {
            unset($map["stock_id"]);
        }
        
//        print_r($map);exit;
    }
    

    
    public function add() {
        $name = $this->getActionName();
        $model = D($name);
        $fields = $model->getDbFields();
        foreach($fields as $k=>$f) {
            if($f == "id") {
                unset($fields[$k]);
            }
        }
        
        import("@.Form.Form");
        $form = new Form(MODULE_NAME);
        $this->assign("FormHTML", $form->makeForm());
        
        $this->assign("fields", $fields);
        $this->display();
    }
    
    
    public function index($name = "") {
        //列表过滤器，生成查询Map对象
        $map = $this->_search();
        $this->_base_filter($map);
//        print_r($map);exit;
        if (method_exists($this, '_filter')) {
            $this->_filter($map);
        }
        $name = $name ? $name : $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $this->_list($model, $map);
        }
        $this->display();
    }
    
    public function viewDetail($model = "") {
        $id = abs(intval($_GET["id"]));
        $name = $model ? $model : $this->getActionName();
        $model = D($name);
        $this->assign("vo", $model->find($id));
        $this->display();
    }

    /**
      +----------------------------------------------------------
     * 取得操作成功后要返回的URL地址
     * 默认返回当前模块的默认操作
     * 可以在action控制器中重载
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    function getReturnUrl() {
        return __URL__ . '?' . C('VAR_MODULE') . '=' . MODULE_NAME . '&' . C('VAR_ACTION') . '=' . C('DEFAULT_ACTION');
    }

    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param string $name 数据对象名称
      +----------------------------------------------------------
     * @return HashMap
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _search($name = '') {
        //生成查询条件
        if (empty($name)) {
            $name = $this->getActionName();
        }
//        $name = $this->getActionName();
        $model = D($name);
        $map = array();
        foreach ($model->getDbFields() as $key => $val) {
            if (isset($_REQUEST [$val]) && $_REQUEST [$val] != '') {
                $map [$val] = $_REQUEST [$val];
            }
        }
        return $map;
    }

    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _list($model, $map, $sortBy = '', $asc = false) {
//        var_dump($model);exit;
        //排序字段 默认为主键名
        if (isset($_REQUEST ['order'])) {
            $order = $_REQUEST ['order'];
        } else {
            $order = !empty($sortBy) ? $sortBy : $model->getPk();
        }
        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if (isset($_REQUEST ['sort'])) {
            $sort = $_REQUEST ['sort'] ? 'asc' : 'desc';
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }
        //取得满足条件的记录数
        $count = $model->where($map)->count();
//        echo $model->getLastSql();exit;
        if ($count > 0) {
            import("ORG.Util.Page");
            //创建分页对象
            if (!empty($_REQUEST ['listRows'])) {
                $listRows = $_REQUEST ['listRows'];
            } else {
                $listRows = 20;
            }
            $p = new Page($count, $listRows);
            
            //分页查询数据
            
            if($this->pageExtraUrl) {
                $p->url = $this->pageExtraUrl;
            }
            
            if($this->relation) {
                $model = $model->relation(true);
            }
            $voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
            //
            //分页跳转的时候保证查询条件
            foreach ($map as $key => $val) {
                if (!is_array($val)) {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }
            //分页显示
            $page = $p->show();
            //列表排序显示
            $sortImg = $sort == "desc" ? "icon-arrow-up" : "icon-arrow-down"; //排序图标
//            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式
            //模板赋值显示
//            print_r($voList);exit;
            $this->assign('list', $voList);
            $this->assign('sortField', $_REQUEST["order"]);
            $this->assign('sort', $sort);
            $this->assign('order', $order);
            $this->assign('sortImg', $sortImg);
//            $this->assign('sortType', $sortAlt);
            $this->assign("page", $page);
            
        }
        
        import("@.TableView.TableView");
        $table = new TableView(MODULE_NAME);
        $this->assign("TableView", $table->makeHorizontalTable($voList, $page));
        
        
        
        cookie('_currentUrl_', __SELF__);
        return $count;
    }
    
    function insert($return=false) {
        $name = $this->getActionName();
        $model = D($name);
        
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        //保存当前数据对象
        if($this->relation) {
            $model = $model->relation(true);
        }
        $list = $model->add();
//        echo $model->getLastSql();exit;
        if($return) {
            return $list;
        }
        
        if ($list !== false) { //保存成功
            $this->success('新增成功!',cookie('_currentUrl_'));
        } else {
            //失败提示
            $this->error('新增失败!');
        }
    }

    function read() {
        $this->edit();
    }

    function edit() {
        $name = $this->getActionName();
        $model = M($name);
        $id = $_REQUEST [$model->getPk()];
        $vo = $model->getById($id);
        if(!$vo) {
            $this->errorPage(404);
            return;
        }
        
        import("@.Form.Form");
        $form = new Form(MODULE_NAME);
        $form->isEdit = true;
        $this->assign("FormHTML", $form->makeForm(null, $vo));
        
        $this->assign('vo', $vo);
        $this->display();
    }

    function update() {
        $name = $this->getActionName();
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        // 更新数据
        if($this->relation) {
            $model = $model->relation(true);
        }
        $list = $model->save();
//        echo $model->getLastSql();exit;
        if (false !== $list) {
            //成功提示
            $this->success('编辑成功!',cookie('_currentUrl_'));
        } else {
            //错误提示
            $this->error('编辑失败!');
        }
    }

    /**
      +----------------------------------------------------------
     * 默认删除操作
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    public function delete() {
        //删除指定记录
        $name = $this->getActionName();
        $model = M($name);
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                $list = $model->where($condition)->setField('status', -1);
                if ($list !== false) {
                    $this->success('删除成功！');
                } else {
                    $this->error('删除失败！');
                }
            } else {
                $this->error('非法操作');
            }
        }
    }

    public function foreverdelete() {
        //删除指定记录
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if($this->relation) {
                $model = $model->relation(true);
            }
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                if (false !== $model->where($condition)->delete()) {
                    $this->success('删除成功！');
                } else {
                    $this->error('删除失败！');
                }
            } else {
                $this->error('非法操作');
            }
        }
    }

    public function clear() {
        //删除指定记录
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            if (false !== $model->where('status=1')->delete()) {
                $this->success(L('_DELETE_SUCCESS_'),$this->getReturnUrl());
            } else {
                $this->error(L('_DELETE_FAIL_'));
            }
        }
        $this->forward();
    }
    
    public function changeStatus() {
        $id = abs(intval($_GET["id"]));
        $status = abs(intval($_GET["status"]));
        $name = $this->getActionName();
        $model = D($name);
        if(!empty($model)) {
            $model->where("id=".$id)->save(array("status"=>$status));
        }
//        echo $model->getLastSql();exit;
//        echo cookie('_currentUrl_');exit;
        redirect(cookie('_currentUrl_'));
    }
    
    
    /**
     * 执行下一工作流程
     */
    public function doWorkflow() {
        $mainRowid = abs(intval($_GET["mainrow_id"]));
        $nodeId = abs(intval($_GET["node_id"]));
        if(!$this->workflowAlias or !$mainRowid or !$nodeId) {
           return false; 
        }
        
        $workflow = new Workflow($this->workflowAlias);
        $rs = $workflow->doNext($mainRowid, $nodeId, false, false);
        if(false === $rs) {
            $this->errorPage("403", "not allowed");
            return;
        }
        // 结束信息返回true、或者没有任何返回值时跳转
        if(true === $rs or !$rs) {
            redirect(cookie('_currentUrl_'));
        }
    }
    
    public function errorPage($code, $message="") {
        $this->assign("message", $message);
        $this->display("../Common:Error:".$code);
    }
    
}

?>
